package com.taobao.clientservice.controller;

import com.taobao.clientservice.entity.Client;
import com.taobao.clientservice.repository.ClientRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/clients")
public class ClientController {
    private final ClientRepository clientRepository;

    public ClientController(ClientRepository clientRepository) {
        this.clientRepository = clientRepository;
    }

    @GetMapping
    public List<Client> getClients() {
        return this.clientRepository.findAll();
    }

    @GetMapping("/{id}")
    public Client getClient(@PathVariable Long id) {
        return this.clientRepository.findById(id).get();
    }

    @PostMapping
    public ResponseEntity createClient(@RequestBody Client client) throws URISyntaxException{
        Client newClient = this.clientRepository.save(client);

        return ResponseEntity.created(new URI("/clients/"+newClient.getId())).body(newClient);
    }

    @PutMapping("/{id}")
    public ResponseEntity updateClient(@PathVariable Long id, @RequestBody Client client){
        Client updateClient = this.clientRepository.findById(id).get();
        updateClient.setName(client.getName());
        updateClient.setEmail(client.getEmail());
        updateClient = this.clientRepository.save(updateClient);

        return ResponseEntity.ok(updateClient);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteClient(@PathVariable Long id){
        Client client = this.clientRepository.findById(id).get();
        this.clientRepository.delete(client);
        return ResponseEntity.ok().build();
    }
}
